package cyy.example.com.facotry;

import android.text.TextUtils;

import com.example.com.common.app.Application;
import com.example.com.common.utils.TimeUtils;
import com.example.com.common.utils.ToastUtil;
import com.example.com.common.utils.Utils;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import org.greenrobot.eventbus.EventBus;

import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

import cyy.example.com.facotry.constants.EventBusConstants;
import cyy.example.com.facotry.data.center.MessageCenter;
import cyy.example.com.facotry.data.center.MessageDispatcher;
import cyy.example.com.facotry.model.EventEntity;
import cyy.example.com.facotry.model.db.MessageModle;
import cyy.example.com.facotry.model.push.BasePushModel;
import cyy.example.com.facotry.model.push.WarningNoticeModel;
import cyy.example.com.facotry.net.RspCode;
import cyy.example.com.facotry.share.SPEngine;

/**
 * Created by chenyiyao on 2017/10/25.
 * des : 负责构造一些全局的配置及工具
 */

public class Factory {

    private static final String TAG = Factory.class.getSimpleName();
    // 单例模式
    private static final Factory instance;
    // 全局的线程池
    private final Executor executor;
    // 全局的Gson
    private final Gson gson;

    static {
        instance = new Factory();
    }

    private Factory() {
        // 新建一个4个线程的线程池
        executor = Executors.newFixedThreadPool(4);
        gson = new GsonBuilder()
                // 设置时间格式
                .setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS")
                // 设置一个过滤器，数据库级别的Model不进行Json转换
//                .setExclusionStrategies(new DBFlowExclusionStrategy())
                .create();
    }

    /**
     * Factory 中的初始化
     */
    public static void setup() {
        Utils.init(app());

    }

    /**
     * 返回全局的Application
     *
     * @return Application
     */
    public static Application app() {
        return Application.getInstance();
    }


    /**
     * 收到账户退出的消息需要进行账户退出重新登录
     */
    private void logout() {

    }

    /**
     * 异步运行的方法
     *
     * @param runnable Runnable
     */
    public static void runOnAsync(Runnable runnable) {
        // 拿到单例，拿到线程池，然后异步执行
        instance.executor.execute(runnable);
    }

    /**
     * 返回一个全局的Gson，在这可以进行Gson的一些全局的初始化
     *
     * @return Gson
     */
    public static Gson getGson() {
        return instance.gson;
    }


    /**
     * 进行错误Code的解析，
     * 把网络返回的Code值进行统一的规划并返回为一个String资源
     *
     * @param netErrorCode 接口返回的code
     */
    public static void decodeRspCode(String netErrorCode) {

        // 进行Code区分
        switch (netErrorCode) {
            case RspCode.SUCCEED:
                return;
            case RspCode.ERROR_ACCOUNT_TOKEN://token错误，重新登录
                ToastUtil.showToastLong(Factory.app(), "账户验证失效，需重新登录");
                EventBus.getDefault().post(new EventEntity(RspCode.ERROR_ACCOUNT_TOKEN, ""));
                break;
            case RspCode.ERROR_ACCOUNT_LOGIN://登录失败
                decodeRspCode(app().getResources().getString(R.string.data_rsp_error_account_login), netErrorCode);
            case RspCode.NET_WORK_ERROR://网络错误
                decodeRspCode(app().getResources().getString(R.string.network_request_error), netErrorCode);
                break;
            case RspCode.SYSTEM_ERROR://登录失败
                decodeRspCode(app().getResources().getString(R.string.data_rsp_error_service), netErrorCode);
                break;
            case RspCode.ERROR_USER_NOT_FIND:
                decodeRspCode("用户不存在", netErrorCode);
                break;

            default:
                decodeRspCode("网络错误", netErrorCode);
                break;
        }

    }

    private static void decodeRspCode(String msg, String code) {
        ToastUtil.showToastShort(Factory.app(), msg);
    }


    /**
     * @param json 消息
     * @param type 类型
     */
    public static void dispatchPush(String json, String type) {
        //非登录状态，无需处理推送消息
        if (!SPEngine.getSPEngine().isLoginState()) return;

        /**
         *  {
         *     "policy": {
         *         "expire_time": "2018-12-06 16:29:01"
         *     },
         *     "description": "测试任务12.3",
         *     "production_mode": false,
         *     "appkey": "5bfba03bf1f5563adf000107",
         *     "payload": {
         *         "body": {
         *             "title": "测试任务标题12.3",
         *             "ticker": "测试任务标题12.3",
         *             "text": "测试任务内容12.3",
         *             "after_open": "go_app",
         *             "play_vibrate": "false",
         *             "play_lights": "false",
         *             "play_sound": "true"
         *         },
         *         "display_type": "notification",
         *         "extra": {
         *             "custom": "name"
         *         }
         *     },
         *     "type": "broadcast",
         *     "timestamp": "1543826272914"
         * }
         */

        if (TextUtils.isEmpty(json)) return;

        if (BasePushModel.WARNING_MSG.equals(type)) {
            WarningNoticeModel data = getGson().fromJson(json, WarningNoticeModel.class);
            if (data != null) {
                MessageModle modle = new MessageModle();
                String content = String.format(Factory.app().getString(R.string.msg_content_temp), data.getCompanyName(), data.getTime(), data.getParamName());
                modle.setContent(content);
                modle.setType(type);
                modle.setTitle("超标预警");
                modle.setContentId(data.getCompanyId());
                modle.setTime(TimeUtils.getNowMills());
                modle.setExtra(json);
                getWarningMsgCenter().dispatch(modle);
                int newMsg = SPEngine.getSPEngine().getUserInfo().getNewMsg();
                SPEngine.getSPEngine().getUserInfo().setNewMsg(newMsg + 1);
                //通知界面刷新
                EventBus.getDefault().post(new EventEntity(EventBusConstants.PUSH_MSG, newMsg));
            }
        }
    }


    public static MessageCenter getWarningMsgCenter() {
        return MessageDispatcher.instance();
    }


}
